<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2018/2/24
 * Time: 10:36
 */

namespace app\console\controller\goods;

use app\common\controller\Console;
use think\Exception;
use think\Log;

class Item extends Console
{
    public function _empty()
    {
        return $this->fetch();
    }

    public function index()
    {
        $result = model('ItemCates')->paginate(10, false, ['query'=>request()->param()])->each(function($item, $key){
            $info = model('Items') -> where('item_cate_id', $item->id)->select();
            $res = '';
            foreach ($info as $v) {
                $res .= $v['name'] . "\t";
            }
            $item->values = $res;
        });
        $this->assign([
            'result' => $result
        ]);
        return $this->fetch();
    }

    public function insert()
    {
        $data = request()->post();
        $item_cate_model = model('ItemCates');
        $item_model = model('Items');
        $item_cate_model->startTrans();
        $item_data = explode("\r\n", $data['values']);
        try {
            $item_cate_id = $item_cate_model->insertGetId(['name' => $data['name']]);
            $dataAll = [];
            foreach ($item_data as  $v) {
                $dataAll[] = [
                    'item_cate_id' => $item_cate_id,
                    'name' => $v
                ];
            }
            $item_model->insertAll($dataAll);
            $item_cate_model->commit();
            $this->success('添加成功');
        } catch (Exception $e) {
            Log::record($e->getMessage());
            $item_cate_model->rollback();
            $this->error('添加失败');
        }

    }

    public function edit($id)
    {
        $info = model('ItemCates')->where('id', $id)->find();
        $res = model('Items')->where('item_cate_id', $id)->select();
        $values = '';
        foreach ($res as $v) {
            $values .= $v['name'] . "\r\n";
        }
        $this->assign([
            'info' => $info,
            'values' => $values
        ]);
        return $this->fetch();
    }

    public function update()
    {
        $data = request()->post();
        if (trim($data['values'])) {
            $item_data = explode("\r\n", $data['values']);
            $dataAll = [];
            foreach ($item_data as  $v) {
                $dataAll[] = [
                    'item_cate_id' => $data['id'],
                    'name' => $v
                ];
            }
            model('Items')->insertAll($dataAll);
        }
        model('ItemCates')->save(['name' => $data['name']], ['id' => $data['id']]);
        $this->success('保存成功');
    }

    public function del($id)
    {
        model('ItemCates')->where('id', $id)->delete();
        return $this->redirect($_SERVER['HTTP_REFERER']);
    }
}
